

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="设计、编制并调试一个词法分析程序，加深对词法分析原理的理解。利用最小化DFA做词法分析。">
<meta property="og:type" content="article">
<meta property="og:title" content="基于DFA的词法分析（一）：程序框架及数据结构">
<meta property="og:url" content="https://cheney822.gitee.io/2021/04/19/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86__%E5%9F%BA%E4%BA%8EDFA%E7%9A%84%E8%AF%8D%E6%B3%95%E5%88%86%E6%9E%90%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E7%A8%8B%E5%BA%8F%E6%A1%86%E6%9E%B6%E5%8F%8A%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="设计、编制并调试一个词法分析程序，加深对词法分析原理的理解。利用最小化DFA做词法分析。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-19T00:22:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:27.575Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="C++">
<meta property="article:tag" content="编译原理">
<meta property="article:tag" content="DFA">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>基于DFA的词法分析（一）：程序框架及数据结构 - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="基于DFA的词法分析（一）：程序框架及数据结构">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-04-19 08:22" pubdate>
        2021年4月19日 早上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.8k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      19 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">基于DFA的词法分析（一）：程序框架及数据结构</h1>
            
            <div class="markdown-body">
              <h2 id="背景："><a href="#背景：" class="headerlink" title="背景："></a>背景：</h2><h2 id="题目描述："><a href="#题目描述：" class="headerlink" title="题目描述："></a>题目描述：</h2><h4 id="一、-实验目的"><a href="#一、-实验目的" class="headerlink" title="一、 实验目的"></a>一、 实验目的</h4><p>设计、编制并调试一个词法分析程序，加深对词法分析原理的理解。</p>
<h4 id="二、-实验要求"><a href="#二、-实验要求" class="headerlink" title="二、 实验要求"></a>二、 实验要求</h4><h5 id="2-1-待分析的简单的词法"><a href="#2-1-待分析的简单的词法" class="headerlink" title="2.1 待分析的简单的词法"></a>2.1 待分析的简单的词法</h5><h6 id="（1）关键字："><a href="#（1）关键字：" class="headerlink" title="（1）关键字："></a>（1）关键字：</h6><ul>
<li><p> begin  if  then  while  do  end</p>
</li>
<li><p> 所有的关键字都是小写。</p>
<h6 id="（2）运算符和界符"><a href="#（2）运算符和界符" class="headerlink" title="（2）运算符和界符"></a>（2）运算符和界符</h6></li>
<li><p>： =  +  -  *  /  &lt;  &lt;=  &lt;&gt;  &gt;  &gt;=  =  ; (  )  #</p>
</li>
</ul>
<h6 id="（3）其他单词是标识符（ID）和整型常数（SUM），通过以下正规式定义："><a href="#（3）其他单词是标识符（ID）和整型常数（SUM），通过以下正规式定义：" class="headerlink" title="（3）其他单词是标识符（ID）和整型常数（SUM），通过以下正规式定义："></a>（3）其他单词是标识符（ID）和整型常数（SUM），通过以下正规式定义：</h6><ul>
<li>ID = letter (letter | digit)*</li>
<li>NUM = digit digit*<h6 id="（4）空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字，词法分析阶段通常被忽略。"><a href="#（4）空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字，词法分析阶段通常被忽略。" class="headerlink" title="（4）空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字，词法分析阶段通常被忽略。"></a>（4）空格有空白、制表符和换行符组成。空格一般用来分隔ID、SUM、运算符、界符和关键字，词法分析阶段通常被忽略。</h6><h5 id="2-2-各种单词符号对应的种别码："><a href="#2-2-各种单词符号对应的种别码：" class="headerlink" title="2.2 各种单词符号对应的种别码："></a>2.2 各种单词符号对应的种别码：</h5></li>
</ul>
<p> <strong>表2.1 各种单词符号对应的种别码</strong> </p>
<table>
<thead>
<tr>
<th>单词符号</th>
<th>种别码</th>
<th>单词符号</th>
<th>种别码</th>
</tr>
</thead>
<tbody><tr>
<td>begin</td>
<td>1</td>
<td>：</td>
<td>17</td>
</tr>
<tr>
<td>if</td>
<td>2</td>
<td>：=</td>
<td>18</td>
</tr>
<tr>
<td>then</td>
<td>3</td>
<td>&lt;</td>
<td>20</td>
</tr>
<tr>
<td>while</td>
<td>4</td>
<td>&lt;&gt;</td>
<td>21</td>
</tr>
<tr>
<td>do</td>
<td>5</td>
<td>&lt;=</td>
<td>22</td>
</tr>
<tr>
<td>end</td>
<td>6</td>
<td>&gt;</td>
<td>23</td>
</tr>
<tr>
<td>lettet（letter / digit）*</td>
<td>10</td>
<td>&gt;=</td>
<td>24</td>
</tr>
<tr>
<td>dight dight*</td>
<td>11</td>
<td>=</td>
<td>25</td>
</tr>
</tbody></table>
<ul>
<li>|   13  |； |   26<br>— |   14 |   (  |  27</li>
</ul>
<ul>
<li> |  15 |   ) |   28<br>/  |  16 |   # |   0<h5 id="2-3-词法分析程序的功能："><a href="#2-3-词法分析程序的功能：" class="headerlink" title="2.3 词法分析程序的功能："></a>2.3 词法分析程序的功能：</h5>输入：所给文法的源程序字符串。<br>输出：二元组（syn,token或sum）构成的序列。<br>其中：</li>
</ul>
<ul>
<li>syn为单词种别码；</li>
<li>token为存放的单词自身字符串；</li>
<li>sum为整型常数;</li>
<li>例如：对源程序begin x:=9: if x&gt;9 then x:=2*x+1/3; end #的源文件，经过词法分析后输出如下序列：<br>(1,begin)(10,x)(18,:=)(11,9)(26, ; )(2,if)……</li>
</ul>
<h2 id="1、程序框架设计："><a href="#1、程序框架设计：" class="headerlink" title="1、程序框架设计："></a>1、程序框架设计：</h2><h3 id="程序的执行过程："><a href="#程序的执行过程：" class="headerlink" title="程序的执行过程："></a>程序的执行过程：</h3><p>执行程序后，系统开始执行初始化操作，初始化包括：读文件录入种别码表、初始化一些全局变量、读取正则表达式录入有穷字母表（默认已经删去程序中用到的操作符，防止出错），然后就是调用分别再三个头文件按中的函数做正则表达式转NFA、NFA确定化、DFA最小化的工作，然后就得到最小化的DFA，随后利用这个DFA读取待分析的源码做词法分析并输出结果。</p>
<p>按照程序的执行顺序，本程序由以下部分构成：</p>
<ul>
<li>正规表达式的读取与处理，种别码表的制作。</li>
<li>正则表达式转NFA</li>
<li>NFA转DFA</li>
<li>DFA最小化                                                                                                                                                                                     </li>
<li>利用最小化DFA做词法分析</li>
</ul>
<h4 id="首先是初始化："><a href="#首先是初始化：" class="headerlink" title="首先是初始化："></a>首先是初始化：</h4><p>利用STL的map结构，first是string类型的字符串second是int类型的种别码，遍历种别码文件将种别码和对应的id分别insert到map中即可。<br>再遍历一遍正则表达式，利用set结构将正则表达式中所有的字符均插入到set中，然后再删去程序中需要用到的操作符。</p>
<h4 id="然后是构建最小DFA"><a href="#然后是构建最小DFA" class="headerlink" title="然后是构建最小DFA"></a>然后是构建最小DFA</h4><p>这部分主要是调用几个头文件中的函数（由组内其他同学完成）</p>
<ul>
<li>NFA n = str_To_Nfa(str);//正则表达式转NFA</li>
<li>DFA d = Nfa_To_Dfa(n);//NFA转DFA    </li>
<li>DFA minDfa = min_DFA(d);//DFA最小化<h4 id="最后是利用DFA做词法分析"><a href="#最后是利用DFA做词法分析" class="headerlink" title="最后是利用DFA做词法分析"></a>最后是利用DFA做词法分析</h4>这里的功能封装进了一个函数：<br><code>void Judge_file2(const char* fp, DFA minD, map&lt;string, int&gt; List);</code><br>函数参数：</li>
<li>Fp：待分析源码存储的文件名</li>
<li>MinD：上述得到的最小化DFA</li>
<li>List：种别码对照表</li>
</ul>
<h5 id="利用DFA词法分析的方法："><a href="#利用DFA词法分析的方法：" class="headerlink" title="利用DFA词法分析的方法："></a>利用DFA词法分析的方法：</h5><p>每次从文件中读取一个字符串（以给定的界符为标志分开），依次分析当前字符串的每个字母，先做特殊处理：判断当前字符串是否为操作符（*，|，&amp;），然后开始利用状态转移矩阵做判断，设置一个信号量存储当前状态（初始值为初态），不断循环遍历字符串，依次将当前状态变换成当前状态接受字符串中一个字母后转移到的状态，如果当前状态变为-1表示无法接收，如果一直到单词的末尾都能接受并且当前状态变为DFA的终态之一，则表示当前字符串可以被DFA识别。<br>对于可以接受的字符串就查表（种别码表），找到与之对应的种别码，然后输出即可。</p>
<h2 id="２、数据结构定义："><a href="#２、数据结构定义：" class="headerlink" title="２、数据结构定义："></a>２、数据结构定义：</h2><p>本程序用到的数据结构包含以下部分：</p>
<ul>
<li>NFA_state_node://标识NFA状态的节点</li>
<li>NFA://表示一个NFA</li>
<li>Edge://表示DFA的一条边</li>
<li>DFA_state_node://标识DFA状态的节点</li>
<li>DFA://表示一个DFA</li>
</ul>
<p>数据结构具体设计方法（代码实现）：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp">set&lt;<span class="hljs-type">char</span>&gt; All_Char;<span class="hljs-comment">//所有的操作数集合(从正则表达式读到的所有种类除去操作符)</span><br>set&lt;<span class="hljs-type">char</span>&gt; Beg;<span class="hljs-comment">//初态的下一状态集合</span><br>set&lt;<span class="hljs-type">char</span>&gt; End;<span class="hljs-comment">//终态的上一状态集合</span><br></code></pre></td></tr></table></figure>

<p>All_Char是本程序可以识别的所有（除了操作符）操作数的集合，从正则表达式中读取得到。<br>Beg是初态能接受的串的集合<br>End是能被接受转移到终态的集合</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">NFA_State_Node</span>				<span class="hljs-comment">/*定义NFA状态*/</span><br>&#123;<br>	<span class="hljs-type">int</span> state_id ;				<span class="hljs-comment">/*NFA状态的状态号*/</span><br>	<span class="hljs-type">char</span> get_value;				<span class="hljs-comment">/*NFA状态弧上的值*/</span><br>	<span class="hljs-type">int</span> Trans_to;			<span class="hljs-comment">/*NFA状态弧转移到的状态号*/</span><br>	set&lt;<span class="hljs-type">int</span>&gt; E_closure_to;			<span class="hljs-comment">/*当前状态通过ε转移到的状态号集合*/</span><br>&#125;;<br></code></pre></td></tr></table></figure>

<p>一个NFA状态节点由以下部分构成：状态号、该状态可以接受的字符、该状态能转移到的状态号、还有一个当前状态通过ε转移到的状态号集合。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">NFA</span><br>&#123;<br>	<span class="hljs-type">int</span> N_StateNum = <span class="hljs-number">0</span>;		<span class="hljs-comment">/*NFA状态总数*/</span><br>	set&lt;<span class="hljs-type">char</span>&gt; Letter_List;		<span class="hljs-comment">/*NFA的有穷字母表*/</span><br>	NFA_State_Node* head;		<span class="hljs-comment">/*NFA的头指针*/</span><br>	NFA_State_Node* tail;	<span class="hljs-comment">/*NFA的尾指针*/</span><br>&#125;;<br>	NFA_State_Node NFA_States[MAX];	<span class="hljs-comment">/*NFA状态数组*/</span><br></code></pre></td></tr></table></figure>

<p>一个NFA由状态数、有穷字母表、头尾指针构成，另外还有一个NFA的状态数组是全局变量（这里本来应该是NFA的成员，但是由于内部含有较多指针，构造函数没有完全设计好，所以这里将其设计为全局的）</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">class</span> <span class="hljs-title class_">DFA</span>			<span class="hljs-comment">/*定义DFA结构*/</span><br>&#123;<span class="hljs-keyword">public</span>:<br>	<span class="hljs-keyword">struct</span> <span class="hljs-title class_">Edge</span>			<span class="hljs-comment">/*定义DFA的转换弧*/</span><br>	&#123;<br>		<span class="hljs-type">char</span> get_value;			<span class="hljs-comment">/*弧上的值*/</span><br>		<span class="hljs-type">int</span> Trans_to;			<span class="hljs-comment">/*弧所指向的状态号*/</span><br>	&#125;;<br></code></pre></td></tr></table></figure>

<p>一条边由该边接受的字符（弧上的值）和该弧转移到的状态构成</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">struct</span> <span class="hljs-title class_">DFA_State_Node</span>		<span class="hljs-comment">/*定义DFA状态*/</span><br>&#123;<br>	<span class="hljs-type">int</span> state_id;			<span class="hljs-comment">/*DFA状态的状态号*/</span><br>	<span class="hljs-type">bool</span> isEnd;			<span class="hljs-comment">/*是否为终态，是为true，不是为false*/</span><br>	set&lt;<span class="hljs-type">int</span>&gt; E_closure_to;		<span class="hljs-comment">/*NFA的ε-move()闭包*/</span><br>	<span class="hljs-type">int</span> Edge_Num;		<span class="hljs-comment">/*DFA状态上的射出弧数*/</span><br>	Edge Edges[MAX];		<span class="hljs-comment">/*DFA状态上的射出弧*/</span><br>&#125;;<br></code></pre></td></tr></table></figure>

<p>一个DFA状态节点由以下部分构成：状态号、是否为终态的标志、该状态上的弧的个数、该状态上的弧数组、还有一个当前状态通过ε转移到的状态号集合。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-type">int</span> Beg_State;				<span class="hljs-comment">/*DFA的初态*/</span><br>set&lt;<span class="hljs-type">int</span>&gt; End_States;			<span class="hljs-comment">/*DFA的终态集*/</span><br><span class="hljs-type">int</span> D_StateNum = <span class="hljs-number">0</span>;			<span class="hljs-comment">/*DFA状态总数*/</span><br>set&lt;<span class="hljs-type">char</span>&gt; Letter_List;		<span class="hljs-comment">/*DFA的有穷字母表*/</span><br><br><span class="hljs-type">int</span> trans[MAX][MAX];		<span class="hljs-comment">/*DFA的转移矩阵*/</span><br><br>DFA_State_Node DFA_States[MAX];		<span class="hljs-comment">/*DFA状态数组*/</span><br></code></pre></td></tr></table></figure>

<p>一个DFA由状态数、有穷字母表、初态编号、终态集合、一个DFA的状态数组和转移矩阵构成<br>状态转移矩阵的含义：<br>状态1通过接收字母b到达状态二，表示为：<br><code>Ans.trans[1][(int)b-(int)*All_Char.begin()] == 2；</code><br><strong>重点是trans的第二维的意义</strong>，由于其是int类型所以只能用ascii码来表示，<br>故用（int）将char类型强制类型转换成对应的ascii码，<br>但是由于有穷字母表一般不能包含所有ascii码表，所以会造成一定的空间的浪费（最小的ascii码前面的所有空间都被浪费）<br>所以我们实际上采用的是某个字符对应有穷字母表内ascii码最小字符的相对位置来判断的<br>所以字符b在转移矩阵中的位置应该是<code>(int)b-(int)*All_Char.begin()</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs cpp">	<span class="hljs-built_in">DFA</span>() &#123;<br>		<span class="hljs-built_in">memset</span>(trans, <span class="hljs-number">-1</span>, <span class="hljs-built_in">sizeof</span>(trans));	<span class="hljs-comment">/*初始化dfa的转移矩阵*/</span><br>		<span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; MAX; i++)<br>		&#123;<br>			DFA_States[i].state_id = i;<br>			DFA_States[i].isEnd = <span class="hljs-literal">false</span>;<br>			<span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> j = <span class="hljs-number">0</span>; j &lt; MAX; j++)<br>			&#123;<br>				DFA_States[i].Edges[j].get_value = <span class="hljs-string">&#x27;#&#x27;</span>;<br>				DFA_States[i].Edges[j].Trans_to = <span class="hljs-number">-1</span>;<br>			&#125;<br>		&#125;<br>	&#125;<br>&#125;;<br></code></pre></td></tr></table></figure>

<p>在DFA构造函数中初始化各个成员<br>其他算法的实现：<br><a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_46291251/article/details/115861892">基于DFA的词法分析（二）：构造DFA</a></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%9F%BA%E7%A1%80/">计算机基础</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/C/">C++</a>
                    
                      <a class="hover-with-bg" href="/tags/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86/">编译原理</a>
                    
                      <a class="hover-with-bg" href="/tags/DFA/">DFA</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/04/20/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86__%E5%9F%BA%E4%BA%8EDFA%E7%9A%84%E8%AF%8D%E6%B3%95%E5%88%86%E6%9E%90%EF%BC%88%E4%BA%8C%EF%BC%89%EF%BC%9A%E6%9E%84%E9%80%A0DFA/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">基于DFA的词法分析（二）：构造DFA</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/05/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86__%E7%B1%BB%20Pascal%E8%AF%AD%E8%A8%80%E8%AF%8D%E6%B3%95%E5%88%86%E6%9E%90%E5%AE%9E%E9%AA%8C%EF%BC%88%E7%AE%80%E6%98%93%E7%89%88%EF%BC%89/">
                        <span class="hidden-mobile">类 Pascal语言词法分析实验（简易版）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
